package queue;

import java.util.Iterator;

/**
 * 仅用head以及tail判断空满 head,tail需要换算成索引值
 * @param <E>
 */
public class ArrayQueue<E> implements Queue<E>, Iterable<E> {
    private E[] array;
    private int head;
    private int tail;

    public ArrayQueue(int capacity) {
        array = (E[]) new Object[capacity + 1];
    }

    @Override
    public Iterator<E> iterator() {
        return null;
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        array[tail] = value;
        tail = (tail + 1) % array.length;
        return false;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E value = array[head];
        head = (head + 1) % array.length;
        return value;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return array[head];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return (tail + 1) % array.length == head;
    }
}
